package app.controllers.product;

import app.Const;
import app.models.product.Group;
import com.google.common.base.Strings;
import goja.mvc.Controller;
import goja.rapid.datatables.DTCriterias;
import goja.rapid.db.DaoKit;

/**
 * <p>
 * The url product/group Controller.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
public class GroupController extends Controller {

    public static final String FROM_ATTR = "g";

    /**
     * The index route.
     * the url /product/group
     */
    public void index() {}

    public void dtlist() {
        final DTCriterias criterias = getCriterias();
        renderDataTables(criterias, Group.class);
    }

    public void create() {
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        Group group = new Group();
        setAttr(FROM_ATTR, group);
        render("./item.ftl");
    }

    public void edit() {
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        Group group = Group.dao.findById(getPara());
        setAttr(FROM_ATTR, group);
        render("item.ftl");
    }

    public void save() {
        final Group group = getModel(Group.class, FROM_ATTR);
        group.set("product_flag", !Strings.isNullOrEmpty(getPara("g.product_flag")) ? Const.YES : Const.NO);
        group.set("index_show", !Strings.isNullOrEmpty(getPara("g.index_show")) ? Const.YES : Const.NO);

        if (!Strings.isNullOrEmpty(getPara("attachment"))) {
            final String attachment_url = getPara("attachment_url");
            group.set("logo", attachment_url);
            group.set("attachment", getPara("attachment"));
        }

        if (DaoKit.isNew(group)) {
            group.set(Const.FIELD_STATUS, 1);
            group.save();
        } else {
            group.update();
        }
        redirect("/product/group");
    }


    public void delete(){
        if (Group.dao.deleteById(getPara())) {
            renderAjaxSuccess();
        } else {
            renderAjaxSuccess();
        }
    }
}